package com.le.edu.controller;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.le.edu.domain.dto.UserQuery;
import com.le.edu.domain.entity.User;
import com.le.edu.domain.vo.UserVO;
import com.le.edu.exception.AppException;
import com.le.edu.page.TableDataInfo;
import com.le.edu.resp.Result;
import com.le.edu.service.UserService;
import com.le.edu.utils.JwtUtils;
import com.le.edu.utils.PasswordEncoder;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Objects;

/**
 * @author Le
 * @create 2024-03-24 21:02
 */
@RestController
@RequiredArgsConstructor
@Tag(name = "用户接口")
@RequestMapping("/user")
public class UserController extends BaseController {
    private final UserService userService;

    @Operation(summary = "修改用户")
    @PutMapping
    public Result<Void> updateUser(@RequestBody User user) {
        userService.checkUsernameUniqueNeUserId(user.getUserId(), user.getUsername());
        String rowPassword = user.getPassword();
        if (StrUtil.isNotBlank(rowPassword)) {
            user.setPassword(PasswordEncoder.encrypt(rowPassword));
        }
        return toAjax(userService.updateById(user));
    }

    @Operation(summary = "新增用户")
    @PostMapping
    public Result<Void> addUser(@RequestBody User user) {
        userService.checkUsernameUnique(user.getUsername());
        user.setPassword(PasswordEncoder.encrypt(user.getPassword()));
        return toAjax(userService.save(user));
    }

    @Operation(summary = "重置密码")
    @PutMapping("/resetPassword")
    public Result<Void> resetPassword(@RequestBody User user) {
        return toAjax(userService.resetPassword(user));
    }

    @Operation(summary = "批量删除用户")
    @DeleteMapping("/{userIds}")
    public Result<Void> remove(@PathVariable("userIds") Long[] userIds, HttpServletRequest request) {
        Long uid = JwtUtils.getUserId(request);
        if (ArrayUtil.contains(userIds, uid)) {
            return Result.fail("不能删除当前用户");
        }
        return toAjax(userService.removeByIds(Arrays.asList(userIds)));
    }

    @Operation(summary = "修改用户状态")
    @GetMapping("/changeStatus")
    public Result<Void> updateStatus(@RequestParam("userId") Long userId,
                                     @RequestParam("status") String status,
                                     HttpServletRequest request) {
        Long uid = JwtUtils.getUserId(request);
        if (uid.equals(userId)) {
            throw new AppException("不能修改自己的状态");
        }
        boolean flag = userService.update(new LambdaUpdateWrapper<User>()
                .eq(User::getUserId, userId)
                .set(User::getStatus, status));
        return toAjax(flag);
    }

    @Operation(summary = "用户分页")
    @PostMapping("/page")
    public TableDataInfo<UserVO> page(@RequestBody UserQuery dto) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
                .eq(User::getDelFlag, "0")
                .like(StrUtil.isNotBlank(dto.getUsername()), User::getUsername, dto.getUsername())
                .eq(StrUtil.isNotBlank(dto.getStatus()), User::getStatus, dto.getStatus())
                .between(Objects.nonNull(dto.getBeginTime()) && Objects.nonNull(dto.getEndTime()),
                        User::getCreateTime, dto.getBeginTime(), dto.getEndTime())
                .orderByDesc(User::getCreateTime);
        Page<UserVO> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        userService.pageUserList(page, wrapper);
        return TableDataInfo.build(page);
    }
}
